#include "score.h"
#include <stdlib.h>

void loadScores(Score* highscores, char* filename)
{	
	FILE * fin;
	char empty[]={"empty"};
	
	int j=0;
	int i;

	fin = fopen(filename, "r");

	while (!feof(fin))
	{
		int score;
		char name[NAME_LEN];

		fscanf(fin,"%d%s", &score, name);
		strcpy(highscores[j].name,name);
		highscores[j].score = score;
		j++;
		//printf("%d\t\t%s\n",score, name);
	}

	fclose(fin);

	if (j<(NSCORES-1))
	{
		for (i=j;i<NSCORES;i++)
		{
			strcpy(highscores[i].name,empty);
			highscores[i].score=0;
		}
	}

}

int addScore(Score* highscores, Score s)
{
	int i,j;
	int temp;
	int tempscore;
	
	if(s.score <= highscores[NSCORES -1].score)
		return -1;
		
	highscores[NSCORES] = s;	
	
	for (i=0;i<NSCORES;i++)
	{
		tempscore=0;

		for (j=i;j<(NSCORES+1);j++)
		{
			if (highscores[j].score>=tempscore) {
				tempscore=highscores[j].score;
				temp=j;
			}
		}

		char name[50];
		int p;

		p=highscores[i].score;
		highscores[i].score=highscores[temp].score;
		highscores[temp].score=p;

		strcpy(name,highscores[i].name);
		strcpy(highscores[i].name,highscores[temp].name);
		strcpy(highscores[temp].name,name);
	}
	
	return 0;

}

void saveScores(Score* highscores, char* filename)
{
	FILE * fout;

	int i;
	
	fout = fopen(filename, "w");

	for (i=0;i<NSCORES;i++)
	{
		fprintf(fout,"%d %s", highscores[i].score, highscores[i].name );

		if(i != (NSCORES -1))
			fprintf(fout,"\n");
	}

	fclose(fout);

}

void printScores(char* title, Score* highscores, int posX, int posY, int titlecolor, int fontcolor, int backcolor, char* video, char* table)
{
	int i;
	
	drawStringAt(title, posX, posY, titlecolor, 0,1, video, table);
	
	for (i = 0; i < NSCORES; ++i)
	{
			drawIntAt(highscores[i].score, posX, posY + i*20 + 40, fontcolor, backcolor,1, video, table);
			drawStringAt(highscores[i].name, posX + 50, posY + i*20 + 40, fontcolor, backcolor,1, video, table);
	}
	
	drawStringAt("Press ESC to exit.", posX, posY + i*20 + 60, 25, 0,1, video, table);
}
